import { mapGetters } from 'vuex'
import componentFunction from './componentFunction.js'
import switchAudioVideoContent from './switchAudioVideoContent'
import draggable from 'vuedraggable'
export default {
  mixins: [componentFunction, switchAudioVideoContent],
  data() {
    return {
      version: '', // sdk版本
      hostUserChangeList: [],
      joinedUserList: [],
      notJoinedUserList: [],

      videoloading: false,
      audioloading: false,
      // 拖动
      draggedContextSetTimeout: null,
      draggedContext: null,
      // 燃气警情
      gasCaseId: null,
      gasCaseDetail: null,
      elementLoadingText: null,
      input: 4,
      memberLoading: false,
      loading: true,
      valid: true,
      newClientNoticeList: [], // 新成员进入通知

      /* 成员视频布局 */
      memberVideoListStatusDefault: 'videoList_bisection',
      memberVideoListStatus: 'videoList_bisection',

      /* 视频布局列表 */
      videoLayoutList: [
        {
          name: this.$t('equallyDividedList'),
          svgName: 'videoMeeting_videoList_bisection',
          params: 'videoList_bisection'
        },
        {
          name: this.$t('rightList'),
          svgName: 'videoMeeting_videoList_right',
          params: 'videoList_right'
        },
        {
          name: this.$t('leftList'),
          svgName: 'videoMeeting_videoList_left',
          params: 'videoList_left'
        },
        {
          name: this.$t('topList'),
          svgName: 'videoMeeting_videoList_top',
          params: 'videoList_top'
        },
        {
          name: this.$t('bottomList'),
          svgName: 'videoMeeting_videoList_bottom',
          params: 'videoList_bottom'
        },
        {
          name: this.$t('upperLGrid'),
          svgName: 'videoMeeting_videoList_bottom_l',
          params: 'videoList_top_l'
        },
        {
          name: this.$t('lowerLGrid'),
          svgName: 'videoMeeting_videoList_top_l',
          params: 'videoList_bottom_l'
        }
      ],

      /* 画面布局列表 */
      pictureLayoutList: [
        {
          name: this.$t('deviceArea'),
          svgName: 'videoMeeting_monitor',
          params: 'monitorType'
        },
        {
          name: this.$t('memberArea'),
          svgName: 'videoMeeting_member',
          params: 'memberType'
        },
        {
          name: this.$t('messageArea'),
          svgName: 'videoMeeting_memberChat',
          params: 'memberChatType'
        }
      ],
      operationStatus: null,
      messageReminderStatus: false, // 新消息状态

      /* 组件展示 */
      componentsObj: {
        monitorType: true,
        memberType: true,
        memberChatType: true,
        operationType: true,
        userListComponentsType: false, // 是否展开成员操作
        hostUserChangeComponentsType: false, // 是否展开更换主持人
        sceneVideoMeetingType: false // 第一现场会议
      }, // 组件展示
      userListStatus: 'joinedUserList', // joinedUserList || notJoinedUserList

      /* 成员视频数据 */
      transcribeClientIdList: [],
      memberVideoListV2: [],
      unprocessedList: [], // 未处理数据 （当 consumerPaused无数据处理的时候先存储，等数据加入房间后处理）
      userList: [], // 成员列表
      memberVideoList: [], // 加入房间并且打开画面的成员
      closeScreenList: [], // 关闭屏幕数据，
      inPlaceClientIdList: [], // 房间里面的人员信息
      speakingDeviceList: [], // 正在讲话设备
      deviceList: [], // 正在监控的设备列表

      /* 会议设置 */
      meetingSettingsVisible: false,
      /*  个人麦克风 || 摄像头 操作 */
      localVideoStatus: false, // 是否有麦克风 || 摄像头
      audioStatus: true, // 是否有麦克风
      audioPush: true, // 麦克风开关操作
      audioContent: '', // 麦克风提示语

      shareScreenTracks: null, // 屏幕轨道
      videoTracks: null,
      videoStatus: true, // 是否有摄像头
      videoPush: true, // 摄像头开关操作
      videoPushType: true, // 本地摄像头开关状态
      videoContent: '', // 摄像头提示语

      memberHandUp: false, // 成员是否举手
      /*  成员禁言 */
      memberAudioStatus: false, // 是否禁言
      memberAudioContent: '全部成员已开启', // 禁言提示语

      /*  设备音频 */
      memberSoundStatus: false, // 是否静音
      memberSoundContent: this.$t('memberAudioIsOn'), // 禁言提示语

      /* 房间数据 */
      form: {},
      roomId: null,
      uniqueId: null,
      userId: null,
      clientId: null,
      title: this.$t('combinedAction'), // 会议

      shareScreenASender: null, // 共享屏幕发起者
      shareScreenAuth: 1, // 共享屏幕权限(1仅主持人可共享、2允许全体成员共享)
      deviceCommandAuth: 1, // 设备指令权限(1仅主持人可操作、2允许全体成员操作)

      hostUserChangeType: false, // 是否正在更换主持人
      hostUserStatus: true, // 是否是主持人

      /* ==== 共享状态 ==== */
      shareTime: null, // 发起者 10 秒一次通知
      notificationShareStatus: null, // 通知的共享状态
      shareStatus: null, // 共享状态
      shareType: false, // 共享统计开始
      shareCount: 0, // 共享计数 （15秒内没有收到通知就关闭共享）

      /* ==== 页面大屏 ==== */
      currentZoomIn: {},
      drawer: false,

      recordingTime: null,
      recordingCount: 0, // 记录时长（秒）

      noticeOfAbsence: 0 // 未到场通知
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    memberVideoListLength() {
      return this.memberVideoList.length
    },
    /* 计算等比高度 */
    // 补充空状态
    supplementingNum() {
      if (this.memberVideoListStatus !== 'videoList_bisection') return
      if (this.memberVideoListLength > 6) {
        const num = this.memberVideoListLength % 3
        if (num) {
          return 3 - num
        }
      } else {
        if (
          this.memberVideoListLength === 3 ||
          this.memberVideoListLength === 5
        ) {
          return 1
        }
      }
      return 0
    },
    /* 计算等比高度 */
    getHeight() {
      return (index) => {
        let num = this.memberVideoList.length
        if (num === 1) {
          return 100
        }
        if (
          this.memberVideoListStatus === 'videoList_top_l' ||
          this.memberVideoListStatus === 'videoList_bottom_l'
        ) {
          if (num <= 2) {
            return 100
          } else {
            if (
              (this.memberVideoListStatus === 'videoList_top_l' &&
                index <= 1) ||
              (this.memberVideoListStatus === 'videoList_bottom_l' &&
                index >= num - 2)
            ) {
              return 70
            }
            return 30
          }
        } else if (this.memberVideoListStatus === 'videoList_bisection') {
          if (num <= 2) {
            return 100
          } else if (num <= 6) {
            return 50
          } else {
            return 33
          }
        } else if (
          this.memberVideoListStatus === 'videoList_left' ||
          this.memberVideoListStatus === 'videoList_right'
        ) {
          num -= 1
          if (index === 0) {
            return 100
          } else {
            return parseInt(100 / num)
          }
        } else {
          if (
            (this.memberVideoListStatus === 'videoList_bottom' &&
              index === 0) ||
            (this.memberVideoListStatus === 'videoList_top' &&
              index === num - 1)
          ) {
            return 70
          } else {
            return 30
          }
        }
      }
    },
    getWidth() {
      return (index) => {
        let num = this.memberVideoList.length
        if (
          this.memberVideoListStatus === 'videoList_top_l' ||
          this.memberVideoListStatus === 'videoList_bottom_l'
        ) {
          if (num === 1) {
            return 100
          }
          const calculate = num - 2
          const itemWidth = parseInt(100 / calculate)
          let largeScreen = 0
          let smallScreen = 1
          if (this.memberVideoListStatus === 'videoList_bottom_l') {
            largeScreen = num - 1
            smallScreen = num - 2
          }
          if (num >= 5) {
            if (index === largeScreen) {
              return itemWidth * (calculate - 1)
            } else {
              return itemWidth
            }
          } else {
            if (index === largeScreen) {
              return 66.66
            } else if (index === smallScreen) {
              return 33
            } else {
              return itemWidth
            }
          }
        } else if (this.memberVideoListStatus === 'videoList_bisection') {
          if (num === 1) {
            return 100
          } else if (num <= 4) {
            return 50
          }
          return 33
        } else if (
          this.memberVideoListStatus === 'videoList_left' ||
          this.memberVideoListStatus === 'videoList_right'
        ) {
          if (num === 1) {
            return 100
          }
          if (index === 0) {
            return 70
          } else {
            return 30
          }
        } else {
          num = num - 1
          if (
            (this.memberVideoListStatus === 'videoList_bottom' &&
              index === 0) ||
            (this.memberVideoListStatus === 'videoList_top' && index === num)
          ) {
            return 100
          } else {
            return parseInt(100 / num)
          }
        }
      }
    },
    hostUserDevice() {
      return this.userList.find((v) => v.isHostUser === true)
    }
  },
  watch: {
    deviceId: function (val) {
      this.filterValue = val.replace(/[^\w]/g, '')
    },
    /* 监听打开摄像头数据 */
    memberVideoList: {
      immediate: true,
      handler: function (val) {
        if (this.memberVideoListV2.length !== val.length) {
          const arr = []
          for (let i = 0; i < val.length; i++) {
            arr.push(i + 1)
          }
          this.memberVideoListV2 = arr
        }
        if (this.memberVideoList.length === 1) {
          this.memberVideoListStatusFn(this.memberVideoListStatusDefault)
        }
        if (
          !(this.memberVideoList.length <= 6 && this.memberVideoList.length > 1)
        ) {
          this.memberVideoListStatusFn('videoList_bisection')
        }
      }
    },
    userList: {
      immediate: true,
      handler: function () {
        const hostUserChangeList = []
        const joinedUserList = []
        const notJoinedUserList = []
        this.userList.forEach((userItem) => {
          const newClientNoticeListIndex = this.newClientNoticeList.findIndex(
            (v) => v.userClientId === userItem.deviceId
          )
          if (newClientNoticeListIndex !== -1) {
            setTimeout(() => {
              this.$message.success(
                `${
                  userItem.name || userItem.devName || this.$t('member')
                } ${this.$t('enter-0')}${this.title}`
              )
            })
            this.newClientNoticeList.splice(newClientNoticeListIndex, 1)
          }
          const type =
            this.hostUserDevice &&
            userItem.deviceId &&
            userItem.deviceId === this.hostUserDevice.deviceId
          if (
            userItem.methodType === 'successfulCall' ||
            userItem.methodType === 'joinTheRoom'
          ) {
            if (userItem.clientRole === 1 && userItem.orgId) {
              hostUserChangeList[type ? 'unshift' : 'push'](userItem)
            }
            joinedUserList[type ? 'unshift' : 'push'](userItem)
          } else {
            notJoinedUserList[type ? 'unshift' : 'push'](userItem)
          }
        })
        this.$nextTick(() => {
          this.hostUserChangeList = hostUserChangeList
          this.joinedUserList = joinedUserList
          this.notJoinedUserList = notJoinedUserList
        })
      }
    }
  },
  components: {
    draggable
  },
  destroyed() {
    if (this.uniqueId) {
      this.$business.videoMeetingUnsubscribe(this.uniqueId)
      this.$business.canvasUnsubscribe(this.uniqueId)
    }
    if (this.roomId) {
      this.mainStore.commit(
        'deleteUserOperationCallback',
        'videoMeeting_consumerResumed'
      )
      this.mainStore.commit(
        'deleteUserOperationCallback',
        'videoMeeting_consumerPaused'
      )
      // this.exitRoomFn()
    }
  },
  mounted() {},
  methods: {
    // 打开即将到期通知
    async expirationNoticeShow(item) {
      if (!this.hostUserStatus) return
      const { duration } = await this.$refs.expirationNotice?.show(item)
      if (duration) {
        this.$set(this.form, 'duration', duration)
      }
    },
    // 暂停consumer消费
    producerPausedByClientId(clientId, kind = 'all') {
      this.$sdk.producerPausedByClientId({
        roomId: this.roomId,
        clientId,
        kind
      })
    },
    // 恢复consumer消费
    producerResumeByClientId(clientId, kind = 'all') {
      this.$sdk.producerResumeByClientId({
        roomId: this.roomId,
        clientId,
        kind
      })
    },
    // 展示主持人画面
    showHostScreen() {
      const item = this.memberVideoList.find((v) => {
        if (
          v.deviceId === this.shareScreenASender ||
          v.deviceUserId === this.shareScreenASender
        ) {
          return true
        }
        return false
      })
      if (item) {
        if (this.currentZoomIn.deviceId) {
          this.exitLargeScreenFn()
        }
        this.$nextTick(() => {
          this.currentZoomInFn(item)
        })
      }
    },
    // 成员列表状态
    userListStatusFn(userListStatus = 'joinedUserList') {
      this.userListStatus = userListStatus
    },
    // 新消息状态
    messageReminderFn(messageReminderStatus) {
      this.messageReminderStatus = messageReminderStatus
    },
    // 提醒房间成员
    memberReminder() {
      const deviceIdList = []
      const userIdList = []
      this.userList.forEach((item) => {
        // clientRole  1人员 2设备
        if (item.clientRole === 1) {
          if (this.userInfo.id !== item.deviceUserId) {
            userIdList.push(item.deviceUserId)
          }
        } else {
          deviceIdList.push(item.deviceId)
        }
      })
      this.$nextTick(() => {
        this.inviteMemberFn(deviceIdList, userIdList)
      })
    },
    /* 提醒 || 邀请 */
    inviteMemberFn(
      deviceIdList = null,
      userIdList = null,
      successText = this.$t('inviteSuccessfully-0')
    ) {
      return new Promise((resolve, reject) => {
        this.$api.videoMeeting
          .inviteMember({
            uniqueId: this.uniqueId,
            deviceIdList: deviceIdList,
            userIdList: userIdList
          })
          .then((res) => {
            if (res.code === 200) {
              resolve()
              this.$message.success(successText)
            }
          })
          .catch(() => {
            reject(new Error(this.$t('inviteFailed')))
            this.$message.error(this.$t('inviteFailed'))
          })
      })
    },
    // 节流
    throttle(fn, delay) {
      return (params) => {
        if (!this.valid) {
          return false
        }
        this.valid = false
        setTimeout(() => {
          fn(params)
          this.valid = true
        }, delay)
      }
    },
    /* ================  布局切换方法 ================ */
    /* 成员布局切换 */
    memberVideoListStatusFn(memberVideoListStatus) {
      return new Promise((resolve, reject) => {
        this.memberLoading = true
        if (this.memberVideoListStatus === memberVideoListStatus) {
          this.memberLoading = false
          return
        }
        this.memberVideoListStatus = memberVideoListStatus
        this.memberLoading = false
        resolve()
      })
    },
    /* 操作类型切换 */
    operationStatusFn(operationStatus = null) {
      /*
       *   画面布局： pictureLayout
       *
       * */
      this.operationStatus = operationStatus
    },
    /* 组件区展示和关闭 */
    componentsFn(name, type) {
      let item = this.componentsObj[name]
      if (typeof type === 'boolean') {
        item = type
      }
      this.$set(this.componentsObj, name, !item)
      this.$nextTick(() => {
        if (name === 'monitorType') {
          if (!this.componentsObj[name] && !this.componentsObj.memberType) {
            this.componentsFn('memberType')
          }
        } else if (name === 'memberType') {
          if (!this.componentsObj[name] && !this.componentsObj.monitorType) {
            this.componentsFn('monitorType')
          }
        } else if (name === 'userListComponentsType') {
          this.userListStatus = 'joinedUserList'
        }
      })
    },
    /* ================  初始化 ================ */
    /* 视频会议mq主题 */
    videoMeetingSubscribe() {
      if (this.uniqueId) {
        this.$business.videoMeetingSubscribe(this.uniqueId, (res) => {
          const { method, data = {} } = res
          console.log('method, data', method, data)
          if (method === 'muted') {
            /* 禁言指令相关操作 */
            if (!this.hostUserStatus) {
              this.mutedFn(data)
            }
          } else if (method === 'videoMeetingIn') {
            this.newClientNoticeList.push({
              userClientId: data.clientId,
              ...data
            })
          } else if (method === 'handUp') {
            // {
            //   "handUpType": 3,
            //   "uniqueId": "1738740934576",
            //   "userClientId": "173874099969517218"
            // }
            this.setItemHandUp(data)
          } else if (method === 'advanceEnd') {
            /* 即将结束MQ通知 */
            this.expirationNoticeShow(data)
          } else if (method === 'modifySvb') {
            /* 修改推送码率 */
            this.modifySvb(data)
          } else if (method === 'deviceMonitor') {
            /* 打开or关闭设备区设备的监控 */
            this.deviceMonitorFn(data)
          } else if (method === 'kickOut') {
            /* 通知成员被踢出房间 */
            this.kickOut(data)
          } else if (method === 'videoMeetingEnd') {
            /* 服务通知视频会议结束 */
            this.videoMeetingEnd(data)
          } else if (method === 'memberChange') {
            /* 服务通知成员变动 */
            this.memberChange()
          } else if (method === 'share') {
            /* 服务通知共享屏幕 shareScreen or 共享画板 shareCanvas */
            this.share(data)
          } else if (method === 'hostUserChange') {
            /* 服务通知更换主持人 */
            this.noticeHostUserChange(data)
          } else if (method === 'authUpdate') {
            /* 服务通知视频会议权限编辑 */
            this.authUpdate(data)
          } else if (method === 'apLocationChange') {
            /* 报警人上报自己的位置后通知web管理员 */
            this.$emit('on-apLocationChange', data)
          } else if (method === 'caseLocationUpdateRequest') {
            /* 报警人和设备 请求修改警情位置通知 */
            this.$emit('on-caseLocationUpdateRequest', data)
          } else if (method === 'deviceReceiveCase') {
            /* 设备已接警通知： */
            this.$emit('on-deviceReceiveCase', data)
          } else if (method === 'msgNotice') {
            /* 视频会议里短信相关的通知： */
            if (this.msgNotice) {
              this.msgNotice(data)
            }
            this.$emit('on-msgNotice', data)
          } else if (method === 'inviteMemberResult') {
            /* 邀请设备加入视频会议的响应 */
            // --web端的mq接收"邀请设备加入视频会议的响应"
            // data:uniqueId, deviceId, errorCode(错误码)
            const clientId = data.deviceId
            const clientIdIndex = this.userList.findIndex((o) => {
              if (o.deviceId) {
                return o.deviceId === clientId
              } else if (o.userClientId) {
                return o.userClientId === clientId
              } else if (o.openClientId) {
                return o.openClientId === clientId
              }
              return false
            })
            const userItem =
              clientIdIndex !== -1 ? this.userList[clientIdIndex] : {}
            const errorCode = data.errorCode
            const errorCodeObj = {
              701: this.$t('inVideoConference'),
              6140: this.$t('failedToJoinVideoConference'),
              3000: '设备响应超时'
            }
            this.$message.error(
              `${userItem.name || userItem.devName || this.$t('member')}${
                errorCodeObj[errorCode] || this.$t('unknownError')
              } (${errorCode})`
            )
          }
        })
      }
    },
    /* 视频会议成员 */
    roomMemberFindAll(uniqueId) {
      if (!uniqueId) return
      return new Promise((resolve) => {
        this.$api.findAll('videoMeeting/member', { uniqueId }).then((res) => {
          if (res.code === 200) {
            resolve(res.data)
          }
        })
      })
    },
    gasCaseDetailFn() {
      return new Promise((resolve) => {
        this.$api.gasCase.detail(this.gasCaseId).then((res) => {
          if (res.code === 200) {
            this.gasCaseDetail = res.data || {}
          }
        })
      })
    },
    /* 获取会议详情 */
    selectFn() {
      return new Promise((resolve) => {
        this.videoMeetingShareEnd()
        this.elementLoadingText = `${this.$t('readyToJoin')}${this.title}`
        window.sessionStorage.setItem('videoMeetingRoomId', this.uniqueId)
        this.$api.videoMeeting
          .videoMeetingIn(this.uniqueId)
          .then(async (res) => {
            if (res.code === 200) {
              const data = res.data
              this.form = {
                ...data,
                bigSvb: data.bigSvb || '3000',
                defaultSvb: data.defaultSvb || '1000'
              }
              this.roomId = this.form.roomId
              this.shareScreenAuth = this.form.shareScreenAuth
              this.deviceCommandAuth = this.form.deviceCommandAuth
              this.hostUserStatus = this.userId === this.form.hostUserId
              if (!this.hostUserStatus) {
                /* 查询禁言状态 */
                this.videoMeetingGetMuted()
                // 获取个人消息
                await this.getPersonalInformation()
              }
              /* 视频会议mq主题 */
              this.videoMeetingSubscribe()
              // /* 视频会议成员 */
              this.roomMemberFindAll(this.uniqueId).then((userList = []) => {
                this.userList = userList
                this.$nextTick(() => {
                  // 不立即邀请成员，所以平台进入后，手动邀请
                  if (this.form.promptlyInvite === 2) {
                    this.memberReminder()
                  }
                  this.setMemberAudioStatus()
                })
              })
              this.$nextTick(() => {
                /* 加入会议前设置 */
                // this.personalMeetingSettings()
                this.elementLoadingText = `${this.$t('joining')}${
                  this.title
                }${this.$t('pleaseWait-0')}`
                this.audioPush = true
                this.videoPush = true
                this.calculagraphFn() // 会议计时器
                setTimeout(() => {
                  this.meetingSettingsSubmit()
                }, 1000)
              })
              resolve()
            }
          })
          .catch((e) => {
            this.elementLoadingText = e.msg || ''
            this.$deleteConfirmationBox({
              deleteTitleImg: 'tips',
              deleteTitle: this.$t('joinFailed'),
              deleteContent: `<div><p>${e.msg} ${this.$t(
                'accessFailed'
              )}</p> <p>${this.$t('pleaseCloseTheBrowserTab')}</p></div>`,
              closeShow: false,
              submitShow: false
            })
            this.windowClose()
          })
      })
    },
    /* 个人会议设置 （设置 是否打开麦克风） */
    personalMeetingSettings() {
      this.elementLoadingText = `${this.title}${this.$t('settingUp')}`
      this.meetingSettingsVisible = true
      this.audioPush = true
      this.videoPush = true
    },
    /* 创建自己的屏幕画面 */
    createYourOwnScreen() {
      // types = {
      //   1: 'videoElement 原本就存在',
      //   2: 'videoElement 新增的'
      // }
      let types = 1
      let videoElement = this.$sdk.getElements({
        deviceId: null,
        clientId: this.clientId,
        roomId: this.roomId
      })
      if (!videoElement) {
        types = 2
        videoElement = document.createElement('video')
        videoElement.id = `${this.clientId}${this.roomId}`
      }
      videoElement.setAttribute('controls', 'false')
      videoElement.setAttribute('playsinline', 'true')
      videoElement.setAttribute('x5-video-player-fullscreen', 'true')
      videoElement.setAttribute('x5-playsinline', 'true')
      videoElement.setAttribute('webkit-playsinline', 'true')
      videoElement.setAttribute('controls', 'false')
      videoElement.setAttribute('x-webkit-airplay', 'true')
      videoElement.id = `${this.clientId}${this.roomId}`
      videoElement.controls = false
      /* 自己的画面需要静音 */
      videoElement.muted = true
      videoElement.className = 'item_video'
      return {
        types,
        videoElement
      }
    },
    /* 关闭视频会议设置，获取摄像头 || 麦克风 并加入会议 */
    async meetingSettingsSubmit() {
      this.meetingSettingsVisible = false
      this.localVideoStatus = false
      this.memberVideoListStatus = null
      this.closeScreenList = []
      this.speakingDeviceList = []
      this.audioInput = 0
      this.videoInput = 0
      this.audioInputList = await this.$sdk.audioInputListFn()
      this.videoInputList = await this.$sdk.videoInputListFn()
      if (this.audioInputList.length) {
        this.audioStatus = true
        if (this.hostUserStatus) {
          this.audioPush = true
          this.audioContent = this.$t('myMicrophoneIsOn')
        } else {
          this.audioPush = false
          this.audioContent = this.$t('myMicrophoneIsOff')
        }
      } else {
        this.audioStatus = false
        this.audioPush = false
        this.audioContent = this.$t('noMicrophone')
      }
      if (this.videoInputList.length) {
        this.videoStatus = true
        this.videoPush = true
        this.videoContent = this.$t('myScreenIsOn')
      } else {
        this.videoStatus = false
        this.videoPush = false
        this.videoContent = this.$t('noCamera')
      }
      this.localVideoStatus = this.audioStatus || this.videoStatus
      this.version = this.$sdk.getVersion ? this.$sdk.getVersion() : ''
      if (this.version !== '0.3.0') {
        if (this.localVideoStatus) {
          const container = document.getElementById('intercomAudioBox')
          const { videoElement } = this.createYourOwnScreen()
          container.append(videoElement)
        }
      }
      this.loading = false
      // // 默认关闭摄像头 和 麦克风
      if (this.audioStatus) {
        this.audioPush = false
        this.audioContent = this.$t('myMicrophoneIsOff')
        setTimeout(() => this.$message.success(this.audioContent))
      } else {
        setTimeout(() =>
          this.$message.error(
            this.$t(
              'noAvailableMicrophoneDetectedPleaseConnectToTheDeviceAndTryAgain'
            )
          )
        )
      }
      if (this.form.audioOnly === 1) {
        // 语音会议不要摄像头
        this.videoStatus = false
        this.videoPush = false
      } else {
        if (this.videoStatus) {
          this.videoPush = false
          this.videoContent = this.$t('myScreenIsOff')
          setTimeout(() => this.$message.success(this.videoContent))
        } else {
          setTimeout(() =>
            this.$message.error(
              this.$t(
                'noAvailableCameraDetectedPleaseConnectToTheDeviceAndTryAgain'
              )
            )
          )
        }
      }
      this.videoMeetingIn(this.roomId)
    },
    /* 进入视频会议 */
    async videoMeetingIn(roomId, roomData = {}) {
      // && this.audioStatus && this.audioPush
      if (this.hostUserStatus) {
        // 视频录制
        this.pecordingScreenFn()
      }
      /*
       * 正常进入会议，准备的内容
       * 1、在 selectFn 中 已经创建了房间消息
       * 2、加入会议 this.$sdk.videoMeetingIn
       * 3、监听用户操作（打开关闭麦克风和摄像头）
       * */
      const userIndex = this.userList.findIndex(
        (v) => v.deviceUserId === this.userId
      )
      if (userIndex !== -1) {
        this.$set(this.userList, userIndex, {
          ...this.userList[userIndex],
          ...this.getUserInfo()
        })
      }
      this.userOperationCallback()
      let audioPush = this.audioPush
      /* 不是主持人，但房间禁言了 */
      if (!this.hostUserStatus && this.memberAudioStatus) {
        audioPush = false
      }
      this.$nextTick(() => {
        this.speakingDeviceListFn()
      })
      if (roomId) {
        let videoElement = null
        let mediaRoomMemberList = []
        if (this.version !== '0.3.0') {
          videoElement = document.getElementById(
            `${this.clientId}${this.roomId}`
          )
        } else {
          mediaRoomMemberList = await this.getMediaRoomMemberList()
        }
        this.sdkVideoMeetingIn({
          containerName: 'intercomAudioBox',
          localPlayElement: videoElement,
          currentName: 'item_video',
          audioPush: audioPush,
          videoPush: this.videoPush,
          roomData: roomData,
          mediaRoomMemberList,
          roomId
        })
      }
    },
    async getMediaRoomMemberList() {
      const { code, data = [] } =
        await this.$api.videoMeeting.roomMemberFindAll(this.uniqueId)
      if (code === 200) {
        return data
      } else {
        return []
      }
    },
    modifySvb(res) {
      if (res.clientId === this.clientId && this.videoPush) {
        const videoStream = this.$sdk.getLocalVideoStream({
          roomId: this.roomId
        })
        const produceOption = {
          encodings: [
            {
              maxBitrate: res.value,
              maxFramerate: 25
            }
          ],
          codecOptions: {
            opusNack: true,
            videoGoogleStartBitrate: 4000,
            videoGoogleMaxBitrate: res.value,
            videoGoogleMinBitrate: res.value
          }
        }
        this.replaceVideoStream(videoStream, produceOption)
      }
    },
    // 通知修改
    async modifySvbNotice(clientId, value) {
      await this.$api.videoMeeting.modifySvbNotice({
        uniqueId: this.form.uniqueId,
        clientId,
        value
      })
    },
    // sdk 加入 videoMeetingIn
    sdkVideoMeetingIn(params) {
      window.sessionStorage.setItem(
        'produceOption',
        JSON.stringify({
          encodings: [
            { maxBitrate: this.form.defaultSvb * 1024, maxFramerate: 25 }
          ],
          codecOptions: {
            opusNack: true,
            videoGoogleStartBitrate: 4000,
            videoGoogleMaxBitrate: this.form.defaultSvb * 1024,
            videoGoogleMinBitrate: this.form.defaultSvb * 1024
          }
        })
      )
      this.$sdk.videoMeetingIn(
        params,
        (res) => {},
        (res) => {
          this.deviceJoinRoomFn(res)
        }
      )
    },
    getUserInfo() {
      return {
        ...this.userInfo,
        clientRole: 1,
        methodTypeV2: true,
        videoPushing: this.videoPush,
        audioPushing: this.audioPush,
        audioContextType: this.audioStatus && this.audioPush,
        methodType: 'successfulCall',
        muted: !this.hostUserStatus && this.memberAudioStatus ? 1 : 2,
        handUp: this.memberHandUp ? 1 : null,
        deviceUserId: this.userId,
        clientId: this.clientId,
        deviceId: this.clientId
      }
    },
    /* 设备加入房间后操作 */
    deviceJoinRoomFn(res) {
      if (res.status === 'newClientNotice') {
        return
      }
      if (res.status !== 'audioContextType') {
        console.warn('res', res.status)
      }
      const userInfoObj = this.getUserInfo()
      const localVideoStatus = () => {
        if (this.videoStatus && this.videoPush) {
          this.setMemberVideoList([{ ...userInfoObj }])
        }
      }
      if (res.clientIdList.length) {
        const resClientIdList = res.clientIdList.filter((v) => {
          const appData = v.appData || {}
          return v.clientId && appData.currentRole !== 'observer'
        })
        if (res.status !== 'audioContextType') {
          this.transcribeClientIdList = res.clientIdList
          // if (res.status === 'canPlay') {
          //   setTimeout(() => {
          //     this.recordingPersonnelChanges()
          //   }, 1000)
          // }
        }
        if (resClientIdList.length) {
          const memberVideoList = []
          if (this.videoStatus && this.videoPush) {
            memberVideoList.push({ ...userInfoObj })
          }
          this.inPlaceClientIdList = [...resClientIdList]
          this.inPlaceClientIdList.forEach((v) => {
            const clientId = v.clientId
            let obj = {}
            const clientIdIndex = this.userList.findIndex((o) => {
              if (o.deviceId) {
                return o.deviceId === clientId
              } else if (o.userClientId) {
                return o.userClientId === clientId
              } else if (o.openClientId) {
                return o.openClientId === clientId
              }
              return false
            })
            if (clientIdIndex !== -1) {
              /* 设备在别处对剑的时候，提示 */
              if (v.errorCode === 701) {
                // v.errorReason = '未进组'
              }
              const clientIdItem = this.userList[clientIdIndex]
              const unprocessedItem = this.getUnprocessedList(
                v.clientId,
                'consumerPaused'
              )
              if (unprocessedItem && v.audioPushing && v.videoPushing) {
                if (unprocessedItem.kind === 'audio') {
                  v.audioPushing = false
                  this.deleteUnprocessedList(v.clientId, 'consumerPaused')
                }
              }
              if (res.status === 'audioContextType') {
                obj = {
                  ...clientIdItem,
                  ...v,
                  methodTypeV2: true,
                  audioContextType: v.audioContextType
                }
              } else {
                obj = {
                  ...clientIdItem,
                  ...v,
                  methodTypeV2: true
                }
              }
              this.$set(this.userList, clientIdIndex, { ...obj })
            } else {
              obj = {
                methodTypeV2: true,
                ...v,
                deviceId: v.clientId
              }
              // this.userList.push({ ...obj })
            }
            if (res.status !== 'audioContextType') {
              if (v.methodType === 'successfulCall' && v.videoPushing) {
                memberVideoList.push({ ...obj })
              }
            }
          })
          this.$nextTick(() => {
            this.speakingDeviceListFn()
            if (res.status !== 'audioContextType') {
              this.setMemberVideoList(memberVideoList)
            }
            this.throttle(this.mediaClientInfoFn, 500)()
          })
        } else {
          localVideoStatus()
        }
      } else {
        localVideoStatus()
      }
    },
    /* 获取客户端信息 */
    mediaClientInfoFn() {
      const clientIdList = []
      this.inPlaceClientIdList.forEach((v) => {
        const clientId = v.clientId
        const clientIdIndex = this.userList.findIndex((o) => {
          if (o.deviceId) {
            return o.deviceId === clientId
          } else if (o.userClientId) {
            return o.userClientId === clientId
          } else if (o.openClientId) {
            return o.openClientId === clientId
          }
          return false
        })
        if (clientIdIndex === -1) {
          clientIdList.push(v.clientId)
        }
      })
      this.$nextTick(() => {
        if (clientIdList.length) {
          this.$api.videoMeeting
            .clientInfo({
              uniqueId: this.uniqueId,
              clientIds: clientIdList.join(',')
            })
            .then((res) => {
              if (res.code === 200) {
                res.data.forEach((v) => {
                  const clientId =
                    v.userClientId || v.deviceUserId || v.deviceId
                  const inPlaceClientItem = this.inPlaceClientIdList.find(
                    (inPlaceClientItem) => {
                      if (v.deviceId) {
                        return v.deviceId === inPlaceClientItem.clientId
                      } else if (v.userClientId) {
                        return v.userClientId === inPlaceClientItem.clientId
                      } else if (v.openClientId) {
                        return v.openClientId === inPlaceClientItem.clientId
                      }
                      return false
                    }
                  )

                  const unprocessedItem = this.getUnprocessedList(
                    clientId,
                    'consumerPaused'
                  )
                  if (
                    unprocessedItem &&
                    inPlaceClientItem.audioPushing &&
                    inPlaceClientItem.videoPushing
                  ) {
                    if (unprocessedItem.kind === 'audio') {
                      v.audioPushing = false
                      this.deleteUnprocessedList(clientId, 'consumerPaused')
                    }
                  }

                  const rowIndex = this.userList.findIndex((o) => {
                    if (v.deviceUserId) {
                      return o.deviceUserId === v.deviceUserId
                    } else if (o.deviceId) {
                      return o.deviceId === v.deviceId
                    }
                    return false
                  })
                  if (rowIndex === -1) {
                    this.userList.push({
                      methodTypeV2: true,
                      ...inPlaceClientItem,
                      ...v,
                      deviceId: clientId
                    })
                    const memberVideoItem = this.memberVideoList.find(
                      (memberVideoItem) =>
                        memberVideoItem.deviceId === v.userClientId
                    )
                    if (memberVideoItem) {
                      this.$set(memberVideoItem, 'isHostUser', v.isHostUser)
                      this.$set(memberVideoItem, 'name', v.name)
                      this.$set(memberVideoItem, 'jobNum', v.jobNum)
                      this.$set(memberVideoItem, 'deviceUserId', v.deviceUserId)
                      this.$set(memberVideoItem, 'devName', v.devName)
                      if (v) {
                        this.$set(memberVideoItem, 'muted', v.muted)
                        this.$set(memberVideoItem, 'handUp', v.handUp)
                        if (v.headImg) {
                          this.$set(memberVideoItem, 'headImg', v.headImg)
                        }
                      }
                    }
                  } else {
                    const clientIdItem = {
                      ...this.userList[rowIndex],
                      ...inPlaceClientItem,
                      ...v,
                      methodTypeV2: true,
                      deviceId: clientId
                    }
                    this.$set(this.userList, rowIndex, clientIdItem)
                    const memberVideoItem = this.memberVideoList.find(
                      (memberVideoItem) =>
                        memberVideoItem.deviceId === v.userClientId
                    )
                    if (memberVideoItem) {
                      this.$set(memberVideoItem, 'isHostUser', v.isHostUser)
                      this.$set(memberVideoItem, 'name', v.name)
                      this.$set(memberVideoItem, 'jobNum', v.jobNum)
                      this.$set(memberVideoItem, 'deviceUserId', v.deviceUserId)
                      this.$set(memberVideoItem, 'devName', v.devName)
                      if (clientIdItem) {
                        this.$set(memberVideoItem, 'muted', clientIdItem.muted)
                        this.$set(
                          memberVideoItem,
                          'handUp',
                          clientIdItem.handUp
                        )
                        if (clientIdItem.headImg) {
                          this.$set(
                            memberVideoItem,
                            'headImg',
                            clientIdItem.headImg
                          )
                        }
                      }
                    }
                  }
                })
                this.$nextTick(() => {
                  this.speakingDeviceListFn()
                })
              }
            })
        }
      })
    },
    /* 正在说话的设备数据 */
    speakingDeviceListFn() {
      const speakingDeviceList = []
      this.userList.forEach((v) => {
        if (v.deviceUserId === this.userId) {
          if (this.audioStatus && this.audioPush && !this.memberAudioStatus) {
            speakingDeviceList.push({ ...v })
          }
        } else if (v.methodType === 'successfulCall') {
          if (
            v.audioContextType ||
            (v.audioPushing && this.version === '0.3.0')
          ) {
            speakingDeviceList.push({ ...v })
          }
        }
      })
      this.$nextTick(() => {
        this.speakingDeviceList = speakingDeviceList
        this.memberVideoList.forEach((memberVideoItem) => {
          const deviceIndex = this.speakingDeviceList.findIndex(
            (deviceItem) => {
              if (deviceItem.deviceId) {
                return deviceItem.deviceId === memberVideoItem.deviceId
              } else if (deviceItem.deviceUserId) {
                return deviceItem.deviceUserId === memberVideoItem.deviceUserId
              }
              return false
            }
          )
          this.$set(memberVideoItem, 'audioContextType', deviceIndex !== -1)
        })
      })
    },

    /* ================  摄像头 || 麦克风 公用方法 ================ */
    // 停止推流成功回调
    consumerPausedCallback(params) {
      const { roomId, clientId, kind } = params || {}
      if (this.roomId === roomId) {
        const index = this.memberVideoList.findIndex(
          (v) => v.deviceId === clientId
        )
        if (index !== -1) {
          if (kind === 'audio') {
            this.$set(this.memberVideoList[index], 'audioPushing', false)
          } else if (kind === 'video') {
            this.setMemberVideoChange('remove', this.memberVideoList[index], {
              index: index
            })
          }
        } else {
          this.addUnprocessedList({
            state: 'consumerPaused',
            clientId,
            res: params
          })
        }
        const userIndex = this.userList.findIndex(
          (v) => v.deviceId === clientId
        )
        if (userIndex !== -1) {
          if (kind === 'audio') {
            this.$set(this.userList[userIndex], 'audioPushing', false)
          } else if (kind === 'video') {
            this.$set(this.userList[userIndex], 'videoPushing', false)
          }
        }
      }
    },
    // 推流成功回调
    consumerResumedCallback(params) {
      const { roomId, clientId, kind } = params || {}
      if (this.roomId === roomId) {
        const index = this.memberVideoList.findIndex(
          (v) => v.deviceId === clientId
        )
        if (index === -1) {
          const closeScreenItem = this.closeScreenList.find(
            (v) => v.deviceId === clientId
          )
          if (closeScreenItem) {
            if (kind === 'audio') {
              this.$set(closeScreenItem, 'audioPushing', true)
            } else if (kind === 'video') {
              this.setMemberVideoChange('increase', closeScreenItem, {})
            }
          }
        } else if (kind === 'audio') {
          this.$set(this.memberVideoList[index], 'audioPushing', true)
        }
        const userIndex = this.userList.findIndex(
          (v) => v.deviceId === clientId
        )
        if (userIndex !== -1) {
          if (kind === 'audio') {
            this.$set(this.userList[userIndex], 'audioPushing', true)
          } else if (kind === 'video') {
            this.$set(this.userList[userIndex], 'videoPushing', true)
          }
        }
      }
    },
    /* 监听房间内用户对摄像头 || 麦克风的操作 */
    userOperationCallback() {
      /* 打开 */
      this.mainStore.commit('addUserOperationCallback', {
        id: 'videoMeeting_consumerResumed',
        operationName: 'consumerResumed',
        callback: (params) => {
          this.consumerResumedCallback(params)
        }
      })
      /* 关闭 */
      this.mainStore.commit('addUserOperationCallback', {
        id: 'videoMeeting_consumerPaused',
        operationName: 'consumerPaused',
        callback: (params) => {
          this.consumerPausedCallback(params)
        }
      })
    },
    /* ================  未处理相关操作 ================ */
    deleteUnprocessedList(clientId, state) {
      const index = this.unprocessedList.findIndex(
        (v) => v.clientId === clientId && v.state === state
      )
      if (index !== -1) {
        this.unprocessedList.splice(index, 1)
      }
    },
    addUnprocessedList(params) {
      this.unprocessedList.push(params)
    },
    getUnprocessedList(clientId, state) {
      const item = this.unprocessedList.find(
        (v) => v.clientId === clientId && v.state === state
      )
      return item ? item.res : null
    },
    /* ================  摄像头相关操作 ================ */
    /* 摄像头切换 */
    async videoPushFn() {
      if (!this.videoStatus) return
      if (this.videoloading) return
      this.videoloading = true
      if (this.videoPush) {
        await this.videoConsumerPaused()
      } else {
        await this.videoConsumerResume()
      }
      this.videoloading = false
    },
    /* 当前获取视频话语权 */
    videoConsumerResume() {
      return new Promise((resolve, reject) => {
        this.$sdk.videoConsumerResume({
          roomId: this.roomId,
          successCallback: async () => {
            this.videoPush = true
            this.videoContent = this.$t('myScreenIsOn')
            this.$message.success(this.videoContent)
            const userInfoObj = this.getUserInfo()
            await this.setMemberVideoChange(
              'increase',
              {
                ...userInfoObj
              },
              { direction: 'unshift' }
            )
            const clientIdItem = this.userList.find(
              (v) => v.deviceUserId === this.userId
            )
            if (clientIdItem) {
              this.$set(clientIdItem, 'videoPushing', this.videoPush)
            }
            resolve({ code: 200 })
          }
        })
      })
    },
    /* 当前释放视频话语权 */
    videoConsumerPaused() {
      return new Promise((resolve, reject) => {
        this.$sdk.videoConsumerPaused({
          roomId: this.roomId,
          successCallback: async () => {
            this.videoPush = false
            this.videoContent = this.$t('myScreenIsOff')
            this.$message.success(this.videoContent)
            const index = this.memberVideoList.findIndex(
              (v) => v.deviceId === this.clientId
            )
            if (index !== -1) {
              await this.setMemberVideoChange(
                'remove',
                this.memberVideoList[index],
                {
                  index
                }
              )
              const clientIdItem = this.userList.find(
                (v) => v.deviceUserId === this.userId
              )
              if (clientIdItem) {
                this.$set(clientIdItem, 'videoPushing', this.videoPush)
              }
              this.$sdk.videoConsumerPaused({
                roomId: this.roomId,
                successCallback: () => resolve({ code: 200 })
              })
            }
            resolve({ code: 200 })
          }
        })
      })
    },

    /* 成员视频切换 */
    setMemberVideoChange(type, item = {}, { index, direction = 'push' }) {
      /*
       * type： remove 移除 increase 新增
       * direction： unshift 从前面添加 push 从后门添加
       * */
      return new Promise((resolve, reject) => {
        const parent = document.getElementById('intercomAudioBox')
        const el = this.$sdk.getElements({
          deviceId: item.deviceId,
          roomId: this.roomId
        })
        if (el) {
          parent.append(el)
        }
        if (type === 'remove') {
          /* 存储关闭摄像头的数据 */
          this.closeScreenList.push({ ...item, videoPushing: false })
          this.memberVideoList.splice(index, 1)
        } else if (type === 'increase') {
          if (direction === 'unshift') {
            this.memberVideoList.unshift({ ...item, videoPushing: true })
          } else if (direction === 'push') {
            this.memberVideoList.push({ ...item, videoPushing: true })
          }
        }
        this.setMemberVideoList(this.memberVideoList)
        this.$nextTick(() => {
          resolve()
        })
      })
    },
    /* 成员视频数据调整 */
    setMemberVideoList(dataList = []) {
      if (dataList.length) {
        const parent = document.getElementById('intercomAudioBox')
        this.memberVideoList.forEach((item) => {
          const el = this.$sdk.getElements({
            deviceId: item.deviceId,
            clientId: item.clientId,
            roomId: this.roomId
          })
          if (el) {
            parent.append(el)
          }
        })
        this.memberVideoList = [...dataList]
        console.warn('this.memberVideoList', this.memberVideoList)
        this.$nextTick(() => {
          this.memberVideoList.forEach((item) => {
            if (typeof item.memberSoundStatus !== 'boolean') {
              item.memberSoundStatus = this.memberSoundStatus
              this.$set(item, 'memberSoundStatus', this.memberSoundStatus)
            }
            if (item.videoPushing) {
              const el = document.getElementById(`itemId_${item.deviceId}`)
              const childEl = this.$sdk.getElements({
                deviceId: item.deviceId,
                clientId: item.clientId,
                roomId: this.roomId
              })
              if (el && childEl) {
                childEl.classList.add('item_video')
                if (item.deviceId !== this.clientId) {
                  childEl.muted = item.memberSoundStatus
                }
                el.appendChild(childEl)
              }
            }
          })
        })
      } else {
        this.memberVideoList = []
      }
    },

    /* ================ 麦克风相关操作 ================ */
    /* 麦克风切换 */
    async audioPushFn() {
      if (!this.audioStatus) return

      if (this.audioloading) return
      if (this.audioPush) {
        await this.audioConsumerPaused()
      } else {
        await this.audioConsumerResume()
      }
      this.audioloading = false
    },
    /* 当前获取视频话语权 */
    audioConsumerResume() {
      return new Promise((resolve, reject) => {
        this.$sdk.audioConsumerResume({
          roomId: this.roomId,
          successCallback: () => {
            this.audioPush = true
            this.audioContent = this.$t('myMicrophoneIsOn')
            this.$message.success(this.audioContent)

            const clientIdItem = this.userList.find(
              (v) => v.deviceUserId === this.userId
            )
            if (clientIdItem) {
              this.$set(clientIdItem, 'audioPushing', this.audioPush)
              this.$set(clientIdItem, 'audioContextType', this.audioPush)
            }
            const memberVideoItem = this.memberVideoList.find(
              (memberVideoItem) => memberVideoItem.deviceUserId === this.userId
            )
            if (memberVideoItem) {
              this.$set(memberVideoItem, 'audioPushing', this.audioPush)
              this.$set(memberVideoItem, 'audioContextType', this.audioPush)
            }
            this.$nextTick(() => {
              this.speakingDeviceListFn()
              // setTimeout(() => {
              //   this.recordingPersonnelChanges()
              // }, 500)
              resolve({ code: 200 })
            })
          }
        })
      })
    },
    /* 当前释放视频话语权 */
    audioConsumerPaused() {
      return new Promise((resolve, reject) => {
        this.$sdk.audioConsumerPaused({
          roomId: this.roomId,
          successCallback: () => {
            this.audioPush = false
            this.audioContent = this.$t('myMicrophoneIsOff')
            this.$message.success(this.audioContent)

            const clientIdItem = this.userList.find(
              (v) => v.deviceUserId === this.userId
            )
            if (clientIdItem) {
              this.$set(clientIdItem, 'audioPushing', this.audioPush)
              this.$set(clientIdItem, 'audioContextType', this.audioPush)
            }
            const memberVideoItem = this.memberVideoList.find(
              (memberVideoItem) => memberVideoItem.deviceUserId === this.userId
            )
            if (memberVideoItem) {
              this.$set(memberVideoItem, 'audioPushing', this.audioPush)
              this.$set(memberVideoItem, 'audioContextType', this.audioPush)
            }
            this.$nextTick(() => {
              this.speakingDeviceListFn()
              // setTimeout(() => {
              //   this.recordingPersonnelChanges()
              // }, 500)
              resolve({ code: 200 })
            })
          }
        })
      })
    },
    // 获取个人信息
    async getPersonalInformation() {
      const { code, data = [] } = await this.$api.videoMeeting.clientInfo({
        uniqueId: this.uniqueId,
        clientIds: this.clientId
      })
      if (code !== 200 || data.length === 0) return
      const item = data[0]
      this.memberAudioStatus = item.muted === 1
      this.memberHandUp = item.handUp === 1
      this.memberAudioContent = this.$t('cannotSpeakDuringMuting')
    },
    /* ================ 禁言相关操作 ================ */
    // 设置单个举手状态
    setItemHandUp(params) {
      const handUpType = params.handUpType
      const userClientId = params.userClientId
      this.userList.forEach((userItem) => {
        if (userItem.deviceId === userClientId) {
          setTimeout(() => {
            this.$message.success(
              `${userItem.name || userItem.devName || this.$t('member')} ${
                handUpType === 1 ? '正在举手' : '取消举手'
              }请求发言`
            )
          })
          this.$set(userItem, 'handUp', handUpType)
        }
      })
      this.memberVideoList.forEach((memberVideoItem) => {
        if (memberVideoItem.deviceId === userClientId) {
          this.$set(memberVideoItem, 'handUp', handUpType)
        }
      })
      if (this.clientId === userClientId) {
        this.memberHandUp = handUpType === 1
        if (handUpType === 3) {
          this.$message.error('主持人取消了您的举手发言请求')
        }
      }
    },
    // 视频会议举手
    async setVideoMeetingHandUp(handUpType, userItem) {
      const res = await this.$api.videoMeeting.videoMeetingHandUp({
        uniqueId: this.uniqueId,
        userClientId: userItem ? userItem.deviceId : this.clientId,
        handUpType // 1举手请求、2取消举手、3主持人拒绝
      })
      if (res.code === 200) {
        const type = handUpType === 1
        this.memberHandUp = type
        if (userItem) {
          this.$set(userItem, 'handUp', type)
        }
        if (handUpType === 3) {
          this.$message.success('已取消该成员举手发言')
        }
      }
    },
    // 查询禁言状态(1禁言、2未禁言)
    videoMeetingGetMuted() {
      this.$api.videoMeeting.videoMeetingGetMuted(this.uniqueId).then((res) => {
        if (res.code === 200) {
          const muted = res.data || null
          this.memberAudioStatus = muted === 1
          this.memberAudioContent = this.$t('cannotSpeakDuringMuting')
        }
      })
    },
    /* 主持人禁言 */
    memberAudioFn(userClientId = null, muted = null) {
      this.$api.videoMeeting
        .videoMeetingMuted({
          uniqueId: this.uniqueId,
          muted: muted,
          userClientId // 成员的媒体clientId（全体禁言时不用传）
        })
        .then((res) => {
          if (res.code === 200) {
            this.mutedFn({
              muted,
              userClientId
            })
          }
        })
    },
    setMemberAudioStatus() {
      if (!this.hostUserStatus) return
      let memberAudioStatus = true
      if (this.userList.length === 1 && this.userList[0].isHostUser) {
        if (this.userList[0].muted === 2) {
          memberAudioStatus = false
        }
      } else {
        for (let i = 0; i < this.userList.length; i++) {
          const userItem = this.userList[i]
          if (
            userItem.muted !== 1 &&
            memberAudioStatus &&
            !userItem.isHostUser
          ) {
            memberAudioStatus = false
            break
          }
        }
      }
      this.$nextTick(() => {
        this.memberAudioStatus = memberAudioStatus
        if (this.memberAudioStatus) {
          this.memberAudioContent = this.$t('allMembersMuted')
        } else {
          this.memberAudioContent = this.$t('memberMicrophoneTurnedOn')
        }
      })
    },
    /* 通知禁言or取消禁言 */
    mutedFn({ muted, userClientId }) {
      const memberAudioStatus = muted === 1
      let deviceId = null
      if (this.hostUserStatus) {
        deviceId = this.clientId
      } else {
        deviceId = this.hostUserDevice ? this.hostUserDevice.deviceId : null
      }
      this.$nextTick(() => {
        if (userClientId) {
          const userClientList = userClientId.split(',')
          userClientList.forEach((userDeviceId) => {
            /* 禁言是自己 */
            if (userDeviceId === this.clientId) {
              this.memberAudioStatus = memberAudioStatus
              this.memberHandUp = false
              if (this.memberAudioStatus) {
                this.memberAudioContent = this.$t('cannotSpeakDuringMuting')
                this.$message.success(this.$t('hostHasMutedMemberMicrophones'))
                if (this.audioStatus && this.audioPush) {
                  this.$sdk.audioConsumerPaused({
                    roomId: this.roomId
                  })
                }
              } else {
                this.memberAudioContent = this.$t(
                  'hostHasEnabledMemberMicrophones'
                )
                this.$message.success(
                  this.$t('hostHasEnabledMemberMicrophones')
                )
                if (this.audioStatus && this.audioPush) {
                  this.$sdk.audioConsumerResume({
                    roomId: this.roomId
                  })
                }
              }
            }
            if (deviceId !== userDeviceId) {
              const userIndex = this.userList.findIndex(
                (v) => v.deviceId === userDeviceId
              )
              if (userIndex !== -1) {
                const userItem = this.userList[userIndex]
                this.$set(userItem, 'muted', muted)
                this.$set(userItem, 'handUp', null)
              }
              const memberVideoIndex = this.memberVideoList.findIndex(
                (v) => v.deviceId === userDeviceId
              )
              if (memberVideoIndex !== -1) {
                const memberVideoItem = this.memberVideoList[memberVideoIndex]
                this.$set(memberVideoItem, 'muted', muted)
                this.$set(memberVideoItem, 'handUp', null)
              }
              this.setMemberAudioStatus()
            }
          })
        } else {
          this.memberAudioStatus = memberAudioStatus
          if (this.hostUserStatus) {
            if (this.memberAudioStatus) {
              this.memberAudioContent = this.$t('allMembersMuted')
            } else {
              this.memberAudioContent = this.$t('memberMicrophonesEnabled')
            }
            this.$message.success(this.memberAudioContent)
          } else {
            if (this.memberAudioStatus) {
              this.memberAudioContent = this.$t('cannotSpeakDuringMuting')
              this.$message.success(this.$t('hostHasMutedMemberMicrophones'))
              if (this.audioStatus && this.audioPush) {
                this.$sdk.audioConsumerPaused({
                  roomId: this.roomId
                })
              }
            } else {
              this.memberAudioContent = this.$t(
                'hostHasEnabledMemberMicrophones'
              )
              this.$message.success(this.$t('hostHasEnabledMemberMicrophones'))
              if (this.audioStatus && this.audioPush) {
                this.$sdk.audioConsumerResume({
                  roomId: this.roomId
                })
              }
            }
          }
          this.userList.forEach((userItem) => {
            if (deviceId && userItem.deviceId === deviceId) {
              this.$set(userItem, 'muted', 2)
            } else {
              this.$set(userItem, 'muted', muted)
            }
            this.$set(userItem, 'handUp', null)
          })
          this.memberVideoList.forEach((memberVideoItem) => {
            if (deviceId && memberVideoItem.deviceId === deviceId) {
              this.$set(memberVideoItem, 'muted', 2)
            } else {
              this.$set(memberVideoItem, 'muted', muted)
            }
            this.$set(memberVideoItem, 'handUp', null)
          })
          this.memberHandUp = false
        }
        this.speakingDeviceListFn()
      })
    },

    /* ================ 静音相关操作 ================ */
    memberSoundFn(deviceId) {
      let memberSoundStatus = true
      if (deviceId) {
        this.memberVideoList.forEach((item) => {
          if (item.deviceId !== this.clientId) {
            if (item.deviceId && item.deviceId === deviceId) {
              const el = this.$sdk.getElements({
                deviceId: item.deviceId,
                roomId: this.roomId
              })
              if (el) {
                el.muted = !el.muted
              }
              this.$set(item, 'memberSoundStatus', !item.memberSoundStatus)
            }
          }
        })
        this.userList.forEach((item) => {
          if (item.deviceId !== this.clientId) {
            if (item.deviceId && item.deviceId === deviceId) {
              this.$set(item, 'memberSoundStatus', !item.memberSoundStatus)
            }
            if (!item.memberSoundStatus && memberSoundStatus) {
              memberSoundStatus = false
            }
          }
        })
      } else {
        /* 全部静音 || 开放声音 */
        memberSoundStatus = !this.memberSoundStatus
        this.memberVideoList.forEach((item) => {
          if (item.deviceId && item.deviceId !== this.clientId) {
            const el = this.$sdk.getElements({
              deviceId: item.deviceId,
              roomId: this.roomId
            })
            if (el) {
              el.muted = memberSoundStatus
            }
            this.$set(item, 'memberSoundStatus', memberSoundStatus)
          }
        })
        this.userList.forEach((item) => {
          if (item.deviceId && item.deviceId !== this.clientId) {
            this.$set(item, 'memberSoundStatus', memberSoundStatus)
          }
        })
      }
      this.$nextTick(() => {
        this.memberSoundStatus = memberSoundStatus
        if (this.memberSoundStatus) {
          this.memberSoundContent = this.$t('allMembersAreMuted')
        } else {
          this.memberSoundContent = this.$t('memberAudioIsOn')
        }
        this.$refs.recordingScreen?.recordingPersonnelChanges()
      })
    },
    /* 通知需要打开or关闭设备区设备的监控 */
    deviceMonitorFn({ deviceId, action }) {
      if (!deviceId) return
      if (action === 'open') {
        if (this.$refs.meetingMonitor) {
          this.$refs.meetingMonitor.deviceDetailFn(deviceId)
        }
      } else {
        if (this.$refs.meetingMonitor) {
          this.$refs.meetingMonitor.deviceCloseFn(deviceId)
        }
      }
    },

    /* ================ 踢人 ================ */
    memberKickOutFn(device) {
      this.$deleteConfirmationBox(
        {
          deleteTitle: this.$t('removeMembers'),
          deleteContent: `<div>
                        <p>${this.$t(
                          'ifTheCurrentMemberIsRemovedTheSubsequentMemberCannotJoinTheCurrentMemberIfNoInvitationIsReceived'
                        )}${this.title}</p>
                        <p>${this.$t('areYouSureToRemoveTheMember')}？</p>
                        </div>`,
          submitText: this.$t('remove')
        },
        () => {
          this.$nextTick(() => {
            this.$api.videoMeeting
              .memberKickOut({
                uniqueId: this.uniqueId,
                userClientId: device.deviceId
              })
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success(
                    `${
                      device.name || device.devName || this.$t('member')
                    } ${this.$t('hasLeft')}${this.title}`
                  )
                }
              })
          })
        }
      )
    },
    /* 通知成员被踢出房间 */
    kickOut({ userClientId }) {
      if (userClientId === this.clientId) {
        if (this.deviceCommandAuth === 2) {
          this.hostUserChangeType = true
        } else {
          // 如果成员无法操作，则直接关闭直播窗口
          this.loading = true
        }
        this.elementLoadingText = this.$t('pleaseCloseTheBrowserTab')
        if (this.videoStatus && this.videoStatus) {
          this.videoConsumerPaused()
        }
        if (this.shareScreenASender === this.userId) {
          if (this.shareStatus === 'shareScreen') {
            this.shareScreenEndFn()
          } else if (this.shareStatus === 'shareCanvas') {
            this.shareScreenEndFn('shareCanvasEnd')
          }
        }
        this.$deleteConfirmationBox({
          deleteTitleImg: 'tips',
          deleteTitle: `${this.title}${this.$t('notification')}`,
          deleteContent: `<div><p>${this.$t('youHaveBeenRemoved')}${
            this.title
          }，${this.$t('cannotJoinLater')}</p><p>${this.$t(
            'pleaseCloseTheBrowserTab'
          )}</p></div>`,
          closeShow: false,
          submitShow: false
        })
        this.windowClose()
      }
    },

    /* ================ 视频会议结束 ================ */
    /* 关闭前操作 */
    closeHandleCommand(command) {
      if (command === 'exitRoomFn') {
        this.exitRoomFn()
      } else if (command === 'videoMeetingEndFn') {
        this.videoMeetingEndFn()
      }
    },
    /* 结束会议 */
    videoMeetingEndFn() {
      this.$deleteConfirmationBox(
        {
          deleteTitleImg: 'tips',
          deleteTitle: '结束会议',
          deleteContent: `<div><p>${this.$t('endTheCurrent')}${
            this.title
          }${this.$t(
            'membersWillBeNotifiedAndCannotJoinLater'
          )}</p><p>${this.$t('areYouSureToEndTheCurrent')}${
            this.title
          }</p></div>`,
          closeText: this.$t('cancel'),
          submitText: this.$t('endTheMeeting')
        },
        () => {
          this.$api.videoMeeting.videoMeetingEnd(this.uniqueId).then((res) => {
            if (res.code === 200) {
              this.loading = true
              this.elementLoadingText = this.$t('pleaseCloseTheBrowserTab')
              this.$deleteConfirmationBox({
                deleteTitleImg: 'tips',
                deleteTitle: `${this.title}${this.$t('notification')}`,
                deleteContent: `<div><p>${this.$t('current')}${
                  this.title
                }${this.$t('ended')} </p><p>${this.$t(
                  'pleaseCloseTheBrowserTab'
                )}</p></div>`,
                closeShow: false,
                submitShow: false
              })
              this.windowClose()
            }
          })
        }
      )
    },
    /* 退出房间 */
    exitRoomFn() {
      const submit = () => {
        if (this.videoStatus && this.videoStatus) {
          this.videoConsumerPaused()
        }
        this.ceaseRecordVideo()
        if (this.shareScreenASender === this.userId) {
          if (this.shareStatus === 'shareScreen') {
            this.shareScreenEndFn()
          } else if (this.shareStatus === 'shareCanvas') {
            this.shareScreenEndFn('shareCanvasEnd')
          }
        }
        this.$nextTick(() => {
          this.$sdk.exitRoomFn(this.roomId)
          this.$message.success(this.$t('exitSuccessfully'))
          if (this.deviceCommandAuth === 2) {
            this.hostUserChangeType = true
          } else {
            // 如果成员无法操作，则直接关闭直播窗口
            this.loading = true
          }
          this.elementLoadingText = this.$t('pleaseCloseTheBrowserTab')
          this.$deleteConfirmationBox({
            deleteTitleImg: 'tips',
            deleteTitle: this.$t('exitSuccessfully'),
            deleteContent: `<div><p>${this.$t(
              'closeTheBrowserTabAfterSuccessfulExit'
            )}</p></div>`,
            closeShow: false,
            submitShow: false
          })
          this.windowClose()
        })
      }
      this.$deleteConfirmationBox(
        {
          deleteTitleImg: 'tips',
          deleteTitle: '离开会议',
          deleteContent: '<div><p>是否确认离开会议？</p></div>',
          closeText: this.$t('cancel'),
          submitText: '离开会议'
        },
        () => {
          submit()
        }
      )
    },
    /* 通知视频会议结束 */
    videoMeetingEnd({ uniqueId }) {
      if (uniqueId === this.uniqueId) {
        this.loading = true
        this.elementLoadingText = this.$t('pleaseCloseTheBrowserTab')
        if (this.videoStatus && this.videoStatus) {
          this.videoConsumerPaused()
        }
        this.$deleteConfirmationBox({
          deleteTitleImg: 'tips',
          deleteTitle: `${this.title}${this.$t('notification')}`,
          deleteContent: `<div><p>${this.$t('current')}${this.title}${this.$t(
            'ended'
          )} </p><p>${this.$t('pleaseCloseTheBrowserTab')}</p></div>`,
          closeShow: false,
          submitShow: false
        })
        this.windowClose()
      }
    },

    /* ================ 服务通知成员变动 ================ */
    memberChange() {
      this.roomMemberFindAll(this.uniqueId).then((userList = []) => {
        userList.forEach((userItem) => {
          const deviceUserId = userItem.deviceUserId
          const deviceId = userItem.deviceId
          const index = this.userList.findIndex((row) => {
            if (row.deviceUserId) {
              return row.deviceUserId === deviceUserId
            } else if (row.deviceId) {
              return row.deviceId === deviceId
            }
            return false
          })
          if (index === -1) {
            this.userList.push({ ...userItem })
          }
        })
      })
    },

    /* ================ 服务通知共享屏幕or共享画板 ================ */
    // 服务通知共享屏幕or共享画板
    share({ uniqueId, share, sender }) {
      // const share = {
      //   shareScreen: '主持人开启共享屏幕',
      //   shareScreenEnd: '主持人关闭共享屏幕',
      //   shareCanvas: '共享画板',
      //   shareCanvasEnd: '共享画板关闭'
      //   shareCanvasStart: '共享页面已打开'
      // }
      this.shareScreenASender = sender
      if (typeof this.userId === 'number') {
        this.shareScreenASender -= 0
      }
      if (uniqueId !== this.uniqueId) return
      if (this.shareScreenASender === this.userId) {
        if (share === 'shareScreen' || share === 'shareCanvas') {
          if (
            this.notificationShareStatus === 'shareScreen' ||
            this.notificationShareStatus === 'shareCanvas'
          ) {
            // 收到了新的通知，所以需要涨停之前的重新计时
            this.shareCount = 0
          } else {
            // 开始计时 规定时间内没有收到通知，自动暂停
            this.shareType = true
            this.shareCount = 0
          }
        } else {
          this.shareCount = 0
          this.shareType = false
        }
      }
      if (this.notificationShareStatus !== share) {
        this.notificationShareStatus = share
        if (share === 'shareScreen') {
          this.$message.success(this.$t('openTheScreenSharing'))
          // 成员需要大屏展示主持人画面
          if (this.shareScreenASender !== this.userId) {
            this.showHostScreen()
          }
        } else if (share === 'shareScreenEnd') {
          this.$message.success(this.$t('closeTheScreenSharing'))
          if (this.shareScreenASender !== this.userId) {
            // if (this.drawer) {
            this.exitLargeScreenFn()
            // }
          }
          this.shareScreenASender = null
        } else if (share === 'shareCanvasStart') {
          // 主持人收到共享页面已打开，进行下一步
          if (this.shareScreenASender === this.userId) {
            this.$message.success(this.$t('pleaseSelectTheWhiteboardPage'))
            this.shareScreenFn('shareCanvas')
          }
        } else if (share === 'shareCanvas') {
          this.$message.success(this.$t('openTheSharedWhiteboard'))
          // 成员需要大屏展示主持人画面
          if (this.shareScreenASender !== this.userId) {
            this.showHostScreen()
            this.$nextTick(() => {
              setTimeout(() => {
                this.initMapsharedWhiteboard()
              }, 500)
            })
          }
        } else if (share === 'shareCanvasEnd') {
          this.$message.success(this.$t('closeTheSharedWhiteboard'))
          if (this.shareScreenASender !== this.userId) {
            // if (this.drawer) {
            this.exitLargeScreenFn()
            // }
          }
          this.shareScreenASender = null
        }
      }
    },
    videoMeetingShareEnd() {
      if (this.shareTime) {
        clearInterval(this.shareTime)
      }
      this.shareTime = null
      this.shareStatus = null
      this.notificationShareStatus = null
    },
    // 发送画板心跳
    videoMeetingShare() {
      if (this.shareTime) {
        clearInterval(this.shareTime)
        this.shareTime = null
      }
      const nextStepFn = () => {
        this.$api.videoMeeting.videoMeetingShare({
          uniqueId: this.uniqueId,
          sender: this.userId,
          share: this.shareStatus
        })
      }
      nextStepFn()
      this.shareTime = setInterval(() => {
        this.videoMeetingShare()
      }, 10000)
    },
    /* ================ 共享屏幕 ================ */
    /* 个人画面切换 */
    replaceVideoStream(videoStream, produceOption) {
      return new Promise((resolve, reject) => {
        const tracks =
          videoStream.getVideoTracks().length > 0
            ? videoStream.getVideoTracks()[0]
            : 0
        // 有摄像头的时候，才需要切换摄像头
        // if (this.videoPush) {
        this.$sdk.replaceVideoStream(videoStream, this.roomId, {
          produceOption: {
            ...produceOption
          }
        })
        // }
        const { videoElement, types } = this.createYourOwnScreen()
        if (videoElement) {
          const stream = new MediaStream()
          const audioStream = this.$sdk.getLocalAudioStream({
            roomId: this.roomId
          })
          if (this.audioStatus && audioStream) {
            stream.addTrack(audioStream.getAudioTracks()[0])
          }
          if (tracks) {
            stream.addTrack(tracks)
          }
          if ('srcObject' in HTMLMediaElement.prototype) {
            videoElement.srcObject = stream
          } else {
            const CompatibleURL = window.URL || window.webkitURL
            videoElement.src = CompatibleURL.createObjectURL(stream)
          }
          videoElement.play()
        }
        if (types === 2) {
          const container = document.getElementById('intercomAudioBox')
          container.append(videoElement)
        }
        resolve(tracks)
      })
    },
    /* 关闭共享屏幕 || 画板 */
    shareScreenEndFn(shareStatus = 'shareScreenEnd') {
      this.shareStatus = shareStatus
      this.videoMeetingShare()
      this.videoMeetingShareEnd()
      if (this.shareScreenTracks) {
        this.shareScreenTracks.stop()
      }
      this.shareScreenTracks = null
      const noCameraFn = () => {
        /* 如果本身就没有摄像头，结束共享就可以释放了 */
        // this.videoStatus = false
        this.videoPush = false
        this.videoContent = this.$t('noCamera')
        this.videoTracks = null
        const clientIdItem = this.userList.find(
          (v) => v.deviceUserId === this.userId
        )
        if (clientIdItem) {
          this.$set(clientIdItem, 'videoPushing', false)
        }
        this.videoConsumerPaused()
      }
      if (!this.videoStatus) {
        noCameraFn()
      } else {
        this.videoConsumerPaused()
        this.getVideoSpecifyContent()
          .then((res) => {
            const initProduceOption = JSON.parse(
              window.sessionStorage.getItem('produceOption') || '{}'
            )
            const produceOption = {
              encodings: [
                { maxBitrate: this.form.defaultSvb * 1024, maxFramerate: 25 }
              ],
              codecOptions: {
                opusNack: true,
                videoGoogleStartBitrate: 4000,
                videoGoogleMaxBitrate: this.form.defaultSvb * 1024,
                videoGoogleMinBitrate: this.form.defaultSvb * 1024
              },
              ...initProduceOption
            }
            this.replaceVideoStream(res.stream, produceOption).then(
              (tracks) => {
                this.videoTracks = tracks
                if (this.videoPushType) {
                  setTimeout(() => {
                    this.videoConsumerResume()
                  }, 500)
                }
              }
            )
          })
          .catch(() => {
            noCameraFn()
          })
        // } else {
        //   this.videoConsumerPaused()
      }
    },
    /* 开启共享屏幕 || 画板 */
    shareScreenFn(shareStatus = 'shareScreen') {
      // 展示个人画面
      const displayPersonalImages = () => {
        if (!this.videoStatus || (this.videoStatus && !this.videoPush)) {
          const userInfoObj = this.getUserInfo()
          this.setMemberVideoChange(
            'increase',
            {
              ...userInfoObj
            },
            { direction: 'unshift' }
          ).then(() => {
            const clientIdItem = this.userList.find(
              (v) => v.deviceUserId === this.userId
            )
            if (clientIdItem) {
              this.$set(clientIdItem, 'videoPushing', true)
            }
            this.videoPush = true
          })
        }
      }
      // 获取屏幕
      this.$sdk
        .getDisplayMedia({ video: true, audio: false })
        .then(async (stream) => {
          const { videoStream } = await this.$sdk.handlerDisplayMediaStream(
            stream
          )
          this.notificationShareStatus = null
          this.shareScreenTracks = videoStream.getVideoTracks()[0]
          this.shareScreenTracks.addEventListener('ended', () => {
            this.shareScreenEndFn(
              shareStatus === 'shareCanvas'
                ? 'shareCanvasEnd'
                : 'shareScreenEnd'
            )
          })
          this.$nextTick(() => {
            this.shareStatus = shareStatus
            this.videoMeetingShare()
            this.videoPushType = this.videoPush
            // 当无摄像头的时候，需要自动开启画面推送
            if (!this.videoPush) {
              this.$sdk.videoConsumerResume({
                roomId: this.roomId,
                stream: videoStream
              })
            }
            const produceOption = {
              encodings: [
                { maxBitrate: this.form.bigSvb * 1024, maxFramerate: 25 }
              ],
              codecOptions: {
                opusNack: true,
                videoGoogleStartBitrate: 4000,
                videoGoogleMaxBitrate: this.form.bigSvb * 1024,
                videoGoogleMinBitrate: this.form.bigSvb * 1024
              }
            }
            this.replaceVideoStream(videoStream, produceOption).then(() => {
              displayPersonalImages()
            })
          })
        })
        .catch((error) => {
          if (shareStatus === 'shareCanvas') {
            this.shareScreenEndFn('shareCanvasEnd')
          }
          this.$message.error(this.$t('failedToObtainTheSharedScreen'))
          console.log(error)
        })
    },

    /* ================ 页面大屏 ================ */
    /* 关闭大屏 */
    exitLargeScreenFn() {
      this.pageFullScreenDisplayFn(false)
      if (this.hostUserStatus) {
        this.modifySvbNotice(this.currentZoomIn.deviceId, this.form.defaultSvb)
      }
      this.$nextTick(() => {
        this.currentZoomIn = {}
        this.$emit('on-currentZoomIn', this.currentZoomIn)
      })
    },
    /* 打开大屏 */
    currentZoomInFn(item) {
      this.currentZoomIn = item
      if (this.hostUserStatus) {
        this.modifySvbNotice(item.deviceId, this.form.bigSvb)
      }
      this.pageFullScreenDisplayFn(true)
      this.$emit('on-currentZoomIn', this.currentZoomIn)
    },
    /* 全屏展示 */
    pageFullScreenDisplayFn(type) {
      const element = document.documentElement
      if (type) {
        this.isFullScreen = !!document.fullscreenElement
        if (!this.isFullScreen) {
          if (element.requestFullscreen) {
            element.requestFullscreen()
          } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen()
          } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen()
          } else if (element.msRequestFullscreen) {
            // IE11
            element.msRequestFullscreen()
          }
        }
      } else {
        if (!this.isFullScreen) {
          if (document.exitFullscreen) {
            document.exitFullscreen()
          } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen()
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen()
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen()
          }
        }
      }
      this.pageFullScreen = type
    },

    /* ========== 会议计时 ========== */
    // 设置即将到期倒计时
    setExpirationNoticeCountdown(currentTime) {
      if (!this.hostUserStatus) return
      this.$refs.expirationNotice?.setCountdown(currentTime)
    },
    // 设置未到场通知
    setNoticeOfAbsence() {
      if (!this.hostUserStatus || this.noticeOfAbsence > 60) return
      this.noticeOfAbsence += 1
      if (this.noticeOfAbsence === 60) {
        const inviteDeviceList = []
        const inviteUserList = []
        this.notJoinedUserList.forEach((item) => {
          if (item.orgId) {
            if (item.clientRole === 1) {
              inviteUserList.push(item.deviceUserId)
            } else {
              inviteDeviceList.push(item.deviceId)
            }
          }
        })
        this.$nextTick(() => {
          if (inviteDeviceList.length && inviteUserList.length) {
            this.$deleteConfirmationBox(
              {
                deleteTitleImg: null,
                deleteTitle: this.title,
                submitClass: 'button_function',
                deleteContent: `${this.title}已开始，是否提醒未到场成员？`,
                closeText: '关闭',
                submitText: '提醒'
              },
              () => {
                this.inviteMemberFn(inviteDeviceList, inviteUserList)
              }
            )
          }
        })
      }
    },
    /* 会议计时器 */
    calculagraphFn() {
      if (this.recordingTime) {
        clearInterval(this.recordingTime)
        this.recordingTime = null
      }
      const startTime = new Date(this.form.startDtm).getTime()
      this.recordingTime = setInterval(() => {
        const currentTime = new Date().getTime()
        this.setExpirationNoticeCountdown(currentTime)
        const recordingCount = currentTime - startTime
        if (recordingCount && recordingCount > 0) {
          this.recordingCount = parseInt(recordingCount / 1000)
          // 新增主持人进入一分钟后，判断人员是否到齐，没有到齐就提醒
          this.setNoticeOfAbsence()
        } else {
          this.recordingCount = 0
        }
        /* 录制时间计算 */
        this.$refs.recordingScreen?.calculagraphFn()
        /* 开始计算是否在共享中 */
        if (this.shareType) {
          this.shareCount += 1
          if (this.shareCount > 20) {
            this.$message.warning(this.$t('ownTimerEnds'))
            this.shareScreenEndFn(
              this.shareStatus === 'shareCanvas'
                ? 'shareCanvasEnd'
                : 'shareScreenEnd'
            )
          }
        }
        if (this.smsNotice) {
          /* 短信通知 */
          this.smsNotice()
        }
      }, 1000)
    },
    /* 整理秒数 为：00:00:00 */
    getSeconds(params) {
      if (!params) {
        return '00:00'
      }
      const clearUp = function (params) {
        return params >= 10 ? params : '0' + params
      }
      const hours = Math.floor(params / 3600)
      const minutes = Math.floor((params % 3600) / 60)
      const seconds = Math.floor(params % 60)
      if (hours) {
        return `${clearUp(hours)}:${clearUp(minutes)}:${clearUp(seconds)}`
      } else {
        return `${clearUp(minutes)}:${clearUp(seconds)}`
      }
    },

    /* ========== 邀请设备 ========== */
    selectDeviceShow(addType) {
      if (addType === 'selectMonitoring') {
        /* 选择监控 */
        this.$refs.meetingMonitor.selectDeviceShow()
      } else if (addType === 'inviteDevices') {
        /* 邀请成员 */
        this.inviteMembersShow()
      } else if (addType === 'smsInvitation') {
        /* 短信邀请 */
      }
    },

    /* ========== 更换主持人 ========== */
    /* 更换主持人 */
    hostUserChange(userItem = {}) {
      const newHostUserId = userItem.deviceUserId
      if (!newHostUserId) return
      this.$deleteConfirmationBox(
        {
          deleteTitleImg: 'tips',
          deleteTitle: this.$t('changeTheHost'),
          deleteContent: `<div>
                  <p>${this.$t('confirmToTransferTheHostAuthorityTo')}</p>
                  <p>${userItem.name} <span class="c_auxiliary">（${
            userItem.jobNum
          }）</span> ？</p>
                </div>`,
          submitClass: 'button_function',
          closeText: this.$t('cancel-0'),
          submitText: this.$t('confirm-5')
        },
        () => {
          /* 停止共享 */
          if (this.shareStatus === 'shareScreen') {
            this.shareScreenEndFn()
          } else if (this.shareStatus === 'shareCanvas') {
            this.shareScreenEndFn('shareCanvasEnd')
          }
          /* 停止录屏 */
          if (this.recordVideoRoomId) {
            this.ceaseRecordVideo()
          }
          this.$api.videoMeeting
            .hostUserChange({
              uniqueId: this.uniqueId,
              newHostUserId: newHostUserId
            })
            .then((res) => {
              if (res.code === 200) {
                this.$message.success(this.$t('operationOperationSuccessful'))
                this.componentsFn('hostUserChangeComponentsType', true)
                this.hostUserChangeType = true
                this.memberAudioStatus = false
                this.memberHandUp = false
                this.elementLoadingText = this.$t('changeTheHostPleaseWait')
              }
            })
        }
      )
    },
    /* 收到更换主持人通知 */
    noticeHostUserChange({
      uniqueId,
      newHostUserId,
      newHostUserName,
      oldHostUserId
    }) {
      if (uniqueId !== this.uniqueId) return
      this.hostUserChangeType = true
      this.elementLoadingText = this.$t('changeTheHostPleaseWait')

      if (this.userId === newHostUserId) {
        if (this.audioStatus && this.audioPush) {
          /* 恢复话语权 */
          this.audioConsumerResume()
        }
        this.$message.success(this.$t('youHaveBecomeTheNewAdministrator'))
        this.hostUserStatus = true
        this.memberAudioStatus = false
        this.memberHandUp = false
      } else {
        this.hostUserStatus = false
        this.$message.success(
          `${this.$t('theHostHasBeenChangedTo')} ${newHostUserName}`
        )
      }
      this.userList.forEach((user) => {
        if (user.isHostUser) {
          this.$set(user, 'muted', 2)
          this.$set(user, 'handUp', null)
          this.$set(user, 'isHostUser', false)
        }
        if (user.deviceUserId === newHostUserId) {
          this.$set(user, 'muted', 2)
          this.$set(user, 'handUp', null)
          this.$set(user, 'isHostUser', true)
        } else {
          this.$set(user, 'isHostUser', false)
        }
      })
      this.memberVideoList.forEach((item) => {
        if (item.deviceUserId === oldHostUserId) {
          this.$set(item, 'muted', 2)
          this.$set(item, 'handUp', null)
          this.$set(item, 'isHostUser', false)
        }
        if (item.deviceUserId === newHostUserId) {
          this.$set(item, 'muted', 2)
          this.$set(item, 'isHostUser', true)
          this.$set(item, 'handUp', null)
        } else {
          this.$set(item, 'isHostUser', false)
        }
      })
      setTimeout(() => {
        this.$nextTick(() => {
          console.log('memberVideoList', [...this.memberVideoList])
          this.hostUserChangeType = false
        })
      }, 500)
    },

    /* ========== 服务通知视频会议权限编辑 ========== */
    authUpdate({ uniqueId, deviceCommandAuth, shareScreenAuth }) {
      if (uniqueId !== this.uniqueId) return
      if (this.hostUserStatus) return
      this.deviceCommandAuth = deviceCommandAuth
      this.shareScreenAuth = shareScreenAuth
      if (shareScreenAuth === 1) {
        // 主持人关闭了成员共享，成员如果正在共享强行退出
        if (this.shareScreenASender === this.userId) {
          if (this.shareStatus === 'shareScreen') {
            this.shareScreenEndFn()
          } else if (this.shareStatus === 'shareCanvas') {
            this.shareScreenEndFn('shareCanvasEnd')
          }
        }
      }
    },
    /* ========== 关闭浏览器页面 ========== */
    windowClose() {
      setTimeout(() => {
        window.parent.postMessage('refuseJoinMeeting', '*')
        window.close()
      }, 5000)
    },
    // ================ 拖拽移动 ====================
    positionExchange(index1, index2) {
      const parent = document.getElementById('intercomAudioBox')
      this.memberVideoList.forEach((item) => {
        if (item.deviceId) {
          const el = this.$sdk.getElements({
            deviceId: item.deviceId,
            roomId: this.roomId
          })
          if (el) {
            parent.append(el)
          }
        }
      })
      if (this.memberVideoList.length < index2) {
        this.memberVideoList[index2] = {}
      }
      this.$nextTick(() => {
        this.memberVideoList[index1] = this.memberVideoList.splice(
          index2,
          1,
          this.memberVideoList[index1]
        )[0]
        this.$nextTick(() => {
          this.memberVideoList.forEach((item) => {
            if (item.deviceId && item.videoPushing) {
              const el = document.getElementById(`itemId_${item.deviceId}`)
              const childEl = this.$sdk.getElements({
                deviceId: item.deviceId,
                roomId: this.roomId
              })
              if (el && childEl) {
                el.append(childEl)
              }
            }
          })
        })
      })
    },
    // 正在拖动回调
    onMove(e) {
      if (this.draggedContextSetTimeout) {
        clearTimeout(this.draggedContextSetTimeout)
      }
      this.draggedContextSetTimeout = setTimeout(() => {
        this.draggedContext = {}
      }, 100)
      if (!this.draggedContext) {
        this.draggedContext = e.draggedContext
      } else if (
        this.draggedContext.futureIndex !== e.draggedContext.futureIndex ||
        this.draggedContext.index !== e.draggedContext.index
      ) {
        this.draggedContext = e.draggedContext
      }
      return false
    },
    // 拖拽结束事件
    onEnd() {
      if (
        this.draggedContext &&
        (this.draggedContext.futureIndex ||
          this.draggedContext.futureIndex === 0)
      ) {
        this.positionExchange(
          this.draggedContext.index,
          this.draggedContext.futureIndex
        )
      }
      this.$nextTick(() => {
        this.draggedContext = {}
        clearTimeout(this.draggedContextSetTimeout)
        this.draggedContextSetTimeout = {}
      })
    }
  }
}
